package com.opennews.openplatform.jooq;

import com.opennews.openplatform.entity.tables.records.UserRecord;
import org.jooq.RecordContext;
import org.jooq.RecordListener;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;

import static com.opennews.openplatform.entity.Tables.USER;

public class UserRecordListener implements RecordListener {
    public void insertStart(RecordContext ctx) {
        // Checks if the record is an instance of UserRecord.
        if (ctx.record() instanceof UserRecord record) {
            encodePassword(record);
            record.setAuthFailedAttempt(0);
            record.setEnabled(true);
            record.setAccountExpired(false);
            record.setAccountLocked(false);
            record.setPasswordExpired(false);
        }
    }

    public void updateStart(RecordContext ctx) {
        // Checks if the record is an instance of UserRecord.
        if (ctx.record() instanceof UserRecord record) {
            if (record.changed(USER.PASSWORD)) {
                encodePassword(record);
            }
        }
    }

    private void encodePassword(UserRecord record) {
        // Apply password encoding logic
        String encodedPassword = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(record.getPassword());
        record.setPassword(encodedPassword);
    }
}
